package com.dizner.androidcartest;

import com.google.android.things.pio.PeripheralManager;
import com.google.android.things.pio.Pwm;

import java.io.IOException;


/**
 * 舵机扩展类
 */
public class SteeringEngine implements AutoCloseable {

    private final Pwm _pwm;
    private int servoMin = 150; // Min pulse length out of 4096
    private int servoMax = 600;  //Max pulse length out of 4096
    private String mSteeringEngineNumber = "";  //PWM舵机编号

    private static final double PULSE_PERIOD_MS = 20;  // Frequency of 50Hz (1000/20)


    public SteeringEngine(String mSteeringEngineNumber) throws IOException {
        this.mSteeringEngineNumber = mSteeringEngineNumber;
        _pwm = PeripheralManager.getInstance().openPwm(mSteeringEngineNumber);
        _pwm.setPwmFrequencyHz(1000 / PULSE_PERIOD_MS);
    }

    private void setServoPulse(int channel, float pulse) {

    }

    public void write(float x) {
        try {
            _pwm.setPwmDutyCycle(x / 15f);
            _pwm.setEnabled(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws Exception {
        if (_pwm != null) {
            _pwm.close();
        }
    }
}
